package com.qf.security;
import com.alibaba.fastjson2.JSON;
import com.qf.util.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/5/8
 * @desc 无权限时异常处理
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置响应头
        response.setStatus(200);
        // 响应类型
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        // 设置返回的提示语句
        String msg = "请求访问："+request.getRequestURI()+"，权限不足，无法访问系统资源";
        // 将Map转换为JSON字符串
        // 此处的JSON是阿里fastjson的jar包,需要导入
        String r = JSON.toJSONString(R.fail( 40003, msg ));
        // 响应出去
        response.getWriter().println(r);
    }
}
